//
//  DefaultsExtension.swift
//  LearningLanguage
//
//  Created by Rui on 2023/8/27.
//

import UIKit
import SnapKit

extension UIView {
    
    func currentViewController() -> UIViewController {
        var next:UIResponder?
        next = self.next
        repeat {
            if ((next as?UIViewController) != nil) {
                return (next as! UIViewController)
            }else {
                next = next?.next
            }
        } while next != nil
        return UIViewController()
    }
    
}

extension UILabel {
    
    /// 添加图片
    /// - Parameter image: 图片
    /// - Parameter rect: 图片
    func attachment(_ image: UIImage?, _ rect: CGRect, _ isFirst: Bool = true) {
        guard let img = image else {return}
        let attributeString = NSMutableAttributedString()
        let attachMent = NSTextAttachment()
        attachMent.image = img
        attachMent.bounds = rect
        if isFirst {
            let imgAttr = NSAttributedString(attachment: attachMent)
            attributeString.append(imgAttr)
            let textArt = NSAttributedString(string: " " + (self.text ?? ""))
            attributeString.append(textArt)
        }else {
            let textArt = NSAttributedString(string: (self.text ?? "") + " " )
            attributeString.append(textArt)
            let imgAttr = NSAttributedString(attachment: attachMent)
            attributeString.append(imgAttr)
        }
        self.attributedText = attributeString
    }
    
}

//MARK: - Double
extension Double {
    /// 适配屏幕宽
    var Fit: CGFloat {
        return CGFloat(self) * .screenWidth / 375.0
    }
    /// 适配屏幕高
    var FitH: CGFloat {
        return CGFloat(self) * .screenHeight / 812.0
    }
}

//MARK: - UIImage
extension UIImage {
    /// 颜色转图片
    /// - Parameter color: 颜色
    /// - Returns: 转换后的图片
    static func colorToImage(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let theImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return theImage!
    }
    
    func compressImage() -> UIImage {
        let tempMaxLength: Int = 2048 / 8
        var compression: CGFloat = 1
        guard var data = self.jpegData(compressionQuality: compression), data.count > tempMaxLength else { return self }
        var max: CGFloat = 1
        var min: CGFloat = 0
        for _ in 0..<6 {
            compression = (max + min) / 2
            data = self.jpegData(compressionQuality: compression)!
            if CGFloat(data.count) < CGFloat(tempMaxLength) * 0.9 {
                min = compression
            } else if data.count > tempMaxLength {
                max = compression
            } else {
                break
            }
        }
        var resultImage: UIImage = UIImage(data: data)!
        if data.count < tempMaxLength { return resultImage }
        var lastDataLength: Int = 0
        while data.count > tempMaxLength && data.count != lastDataLength {
            lastDataLength = data.count
            let ratio: CGFloat = CGFloat(tempMaxLength) / CGFloat(data.count)
            print("Ratio =", ratio)
            let size: CGSize = CGSize(width: Int(resultImage.size.width * sqrt(ratio)),
                                      height: Int(resultImage.size.height * sqrt(ratio)))
            UIGraphicsBeginImageContext(size)
            resultImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
            resultImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            data = self.jpegData(compressionQuality: compression)!
        }
        return resultImage
    }
    func resetImgSize() -> Data {
        var maxSize:CGFloat = 1024.0
        var maxImageSize:CGFloat = 1024.0
        if (maxSize <= 0.0) {
            maxSize = 1024.0
        }
        if (maxImageSize <= 0.0)  {
            maxImageSize = 1024.0
        }
        var newSize = CGSize.init(width: self.size.width, height: self.size.height)
        let tempHeight = newSize.height / maxImageSize
        let tempWidth = newSize.width / maxImageSize
        if (tempWidth > 1.0 && tempWidth > tempHeight) {
            newSize = CGSize.init(width: self.size.width / tempWidth, height: self.size.height / tempWidth)
        }
        else if (tempHeight > 1.0 && tempWidth < tempHeight){
            newSize = CGSize.init(width: self.size.width / tempHeight, height: self.size.height / tempHeight)
        }
        UIGraphicsBeginImageContext(newSize)
        self.draw(in: CGRect.init(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        var imageData = newImage!.jpegData(compressionQuality: 1.0)
        var sizeOriginKB : CGFloat = CGFloat((imageData?.count)!) / 1024.0
        var resizeRate = 0.9
        while (sizeOriginKB > maxSize && resizeRate > 0.1) {
            imageData = newImage!.jpegData(compressionQuality: CGFloat(resizeRate))
            sizeOriginKB = CGFloat((imageData?.count)!) / 1024.0
            resizeRate -= 0.1
        }
        return imageData!
    }
}

extension UIFont {
    
    enum FontType {
        case bold, medium, extraBold
        var fontName: String {
            switch self {
            case .extraBold:
                return "HelveticaNeue-BoldItalic"
            case .bold:
                return "HelveticaNeue-Bold"
            case .medium:
                return "HelveticaNeue-Medium"
            }
        }
        
    }
    static func setTypeFace(_ size: CGFloat!, type: FontType = .bold) -> UIFont {
        if let font = UIFont(name: type.fontName, size: size) {
            return font
        }
        return .systemFont(ofSize: size)
    }

}

//MARK: - CACornerMask
extension CACornerMask {
    static let allCorner: CACornerMask = {
        return [.layerMinXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMaxXMaxYCorner]
    }()
}

extension UIView
{
    func setAllCorners(corner:CGFloat) -> Void {
        self.layer.masksToBounds = true
        self.layer.cornerRadius = corner
    }
}


struct PopUpViewConfig {
    private (set) var view: UIView!
    private (set) var size: CGSize!
    init(view: UIView, size: CGSize) {
        view.tag = 50501
        self.view = view
        self.size = size
    }
}

class Pop_Up_Custom_View: UIView {
    
    /// 点击空白区是否域移除视图，默认为true
    var isCloseFromClean: Bool = true
    
    private (set) var config: PopUpViewConfig?
    
    init(config: PopUpViewConfig,isBottom:Bool = false) {
        super.init(frame: .zero)
        tag = 50502
        self.config = config
        backgroundColor = .blackComponent(0)
        addSubview(config.view)
        config.view.snp.makeConstraints { make in
            if isBottom == true{
                make.left.bottom.equalTo(0)
            }else{
                make.center.equalToSuperview()
            }
            make.size.equalTo(CGSize(width: config.size.width, height: config.size.height))
        }
//        NotificationCenter.default.addObserver(forName: TDNotificationName.receivedAnchorCallingNotification, object: nil, queue: nil) {[weak self] notification in
//            self?.animatedDismiss()
//        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        assert(config != nil, "请使用init(config: PopUpViewConfig)方法初始化")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if isCloseFromClean {
            layoutIfNeeded()
            let touch = touches.first
            guard let point = touch?.location(in: self), let view = config?.view, !view.frame.contains(point) else { return }
            animatedDismiss()
        }
    }
}

extension UIColor{
    
    static func blackComponent(_ alpha: CGFloat) -> UIColor {
        return UIColor.black.withAlphaComponent(alpha)
    }

}

extension UIView {
    
    /// 渐变色枚举
    enum GradientColor: Equatable {
        
        case themeButton
        
        case topToBottom(colors: [UIColor])
        
        case leftToRight(colors: [UIColor])
        
        static func == (lhs: UIView.GradientColor, rhs: UIView.GradientColor) -> Bool {
            return true
        }
        
    }
    
    func removeGradient() {
        if let layers = layer.sublayers {
            for item in layers {
                if item is CAGradientLayer {
                    item.removeFromSuperlayer()
                }
            }
        }
    }
    
    /// 设置渐变色
    /// - Parameter color: 颜色枚举
    func setGrandient(color: GradientColor) {
        clipsToBounds = true
        superview?.layoutIfNeeded()
        let layer = CAGradientLayer()
        layer.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)
        if case .topToBottom(_) = color {
            layer.locations = [0,1]
            layer.startPoint = CGPoint(x: 0, y: 0)
            layer.endPoint = CGPoint(x: 0, y: 1)
        }else if case .themeButton = color {
            layer.startPoint = CGPoint(x: 0, y: 0)
            layer.endPoint = CGPoint(x: 1, y: 0)
            layer.locations = [0,1]
        }else {
            layer.startPoint = CGPoint(x: 0, y: 0)
            layer.endPoint = CGPoint(x: 1, y: 0)
            layer.locations = [0,1]
        }
        self.layer.insertSublayer(layer, at: 0)
    }
    
    /// 按照rect设置渐变色
    /// - Parameters:
    ///   - color: 颜色
    ///   - bounds: rect
    func setGrandient(color: GradientColor, bounds: CGRect) {
        self.clipsToBounds = true
        let layer = CAGradientLayer()
        layer.frame = bounds
        if case .topToBottom(_) = color {
            layer.locations = [0,1]
            layer.startPoint = CGPoint(x: 0, y: 0)
            layer.endPoint = CGPoint(x: 0, y: 1)
        }else if case .themeButton = color {
            layer.startPoint = CGPoint(x: 0, y: 0)
            layer.endPoint = CGPoint(x: 1, y: 0)
            layer.locations = [0,1]
        }else {
            layer.startPoint = CGPoint(x: 0, y: 0)
            layer.endPoint = CGPoint(x: 1, y: 0)
            layer.locations = [0,1]
        }
        self.layer.insertSublayer(layer, at: 0)
    }
    
    /// 当有新弹窗准备弹出时，关闭之前已经弹出的框
    static func dismissBeforePopupView() {
        UIApplication.shared.keyWindow?.subviews.forEach {
            if $0.tag == 50502 {
                $0.animatedDismiss()
            }
        }
    }
    
    /// 弹窗动画
    func animatedPop() {
        if let view = UIApplication.shared.keyWindow {
            view.addSubview(self)
            self.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            var centerView: UIView?
            for v in self.subviews {
                if v.tag == 50501 {
                    centerView = v
                }
            }
            guard centerView != nil else { return }
            centerView?.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
            UIView.animate(withDuration: 0.35, delay: 0.0, options: UIView.AnimationOptions(rawValue: UIView.AnimationOptions.RawValue(7<<16)), animations: {
                centerView?.transform = .identity
                self.backgroundColor = .blackComponent(0.6)
            }, completion: { isFinish in
                
            })
        }
    }
    
    /// 上移动画
    func upAnimatedPop() {
        if let view = UIApplication.shared.keyWindow {
            var centerView: UIView?
            for v in self.subviews {
                if v.tag == 50501 {
                    centerView = v
                }
            }
            guard centerView != nil else { return }
            
            UIView.animate(withDuration: 0.35, delay: 0.0, options: UIView.AnimationOptions(rawValue: UIView.AnimationOptions.RawValue(7<<16)), animations: {
                
                view.addSubview(self)
                self.snp.makeConstraints { make in
                    make.edges.equalToSuperview()
                }
                self.backgroundColor = .blackComponent(0.6)
                
            }, completion: { isFinish in
                
            })
        }
    }

    
    static var popUpViewDismissClosure: (()->Void)?
    
    /// 移除弹窗动画（需要跟弹窗动画配合使用）
    func animatedDismiss() {
        var centerView: UIView?
        for v in self.subviews {
            if v.tag == 50501 {
                centerView = v
            }
        }
        UIView.animate(withDuration: 0.3) {
            self.backgroundColor = .blackComponent(0)
            centerView?.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
        } completion: { isFinish in
            self.removeFromSuperview()
            if let closure = UIView.popUpViewDismissClosure {
                closure()
            }
        }
    }
    
    func downAnimatedDismiss() {
        var centerView: UIView?
        for v in self.subviews {
            if v.tag == 50501 {
                centerView = v
            }
        }
        UIView.animate(withDuration: 0.3) {
            self.backgroundColor = .blackComponent(0)
            centerView?.alpha = 0
        } completion: { isFinish in
            self.removeFromSuperview()
            if let closure = UIView.popUpViewDismissClosure {
                closure()
            }
        }
    }

}

extension Int {
    
    var hourMinuteSecond: String {
        let hour = self / 60 / 60
        let minute = (self - (hour * 60 * 60)) / 60
        let second = (self - (hour * 60 * 60) - (minute * 60))
        var infos = [hour, minute, second]
//        infos.removeAll(where: { $0 <= 0 })
        let times = infos.map({ String(format: "%02d", $0) })
        return times.joined(separator: ":")
    }
    
    var minuteSecond: String {
        let minute = self / 60
        let second = (self - (minute * 60))
        var infos = [minute, second]
//        infos.removeAll(where: { $0 <= 0 })
        let times = infos.map({ String(format: "%02d", $0) })
        return times.joined(separator: ":")
    }
    
    var minute: String {
        let minute = self / 60
        return String(format: "%02dMin", minute)
    }
    
    var minute_int: Int {
        self / 60
    }
    
    var second_int: Int {
        (self - (self / 60 * 60))
    }
    
    ///整型转00:00:00，最大是小时
    func multipleZeroH(showChinese:Bool? = false) -> String {
        var timeStrH:String
        let timeM = self%3600
        let timeS = timeM%60
        print("\(timeM),\(timeS)")
        if showChinese == false {
            timeStrH = String(format: "%02d:%02d:%02d", self/3600, self/60, timeS)
        }else {
            timeStrH = String(format: "%02d小时%02d分%02d秒", self/3600, self/60, timeS)
        }
        
        return timeStrH
    }
    
}
